package service

import (
	"git.oschina.net/fanbuchi/xgggh/oauth2/model"
	account "git.oschina.net/fanbuchi/xgggh/oauth2/proto/account"
	"git.oschina.net/fanbuchi/xgggh/oauth2/db"
	 "git.oschina.net/fanbuchi/xgggh/errs"
	"git.oschina.net/fanbuchi/xgggh/oauth2/utils"
	"context"
	"github.com/jinzhu/gorm"
)


func AccountCreate(ctx context.Context, req *account.CreateReq)(*model.Account,error){
	// If the password is being set already, create a bcrypt hash
	account:=model.Account{UserName:req.UserName,
		RoleId:req.RoleId,
		MetaAccountId:req.MetaAccountId}

	password:=req.Password
	if len(password)==4 {
		password=""
	}

	if  password!= "" {
		if len(password) < errs.MinPasswordLength {
			return nil, errs.PasswordTooShort
		}
		passwordHash, err := utils.HashPassword(password)
		if err != nil {
			return nil, err
		}
		account.Password = string(passwordHash)
	}

	// Check the username is available
	result,err:=AccountSearchByUserName(req.UserName)

	if err!=gorm.ErrRecordNotFound &&err!=nil {
		return nil, err
	}
	if result!=nil&&result.ID>0 {
		return result,nil
	}
	err=db.GetDB().Create(&account).Error
	if err !=nil{
		return nil,err
	}
	return &account,err
}

func  AccountSearchByUserName(userName string) (*model.Account,error) {
	var account  model.Account;
	params:=model.Account{
		UserName: userName,
	}
	err:=db.GetDB().
		Where(params).
		First(&account).
		Error
	return &account,err
}

func  AccountSearch(req *account.SearchReq) ([]*model.Account,error) {
	var accounts [] *model.Account;
	//page
	limit,offset:=SearchPage(req.Page,req.PerPage)

	//support below data filter
	params:=model.Account{
		UserName: req.Params["userName"],
		MetaAccountId:req.Params["metaAccountId"],
	}
	//db
	err:=db.GetDB().
		Where(params).
		Order("id desc").
		Offset(offset).
		Limit(limit).
		Find(&accounts).
		Error
	return  accounts,err
}




